package com.cctc.rds.nrpc.api.connection.server;

import com.cctc.rds.nrpc.api.connection.Connection;
import com.cctc.rds.nrpc.api.connection.ConnectionPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractServerConnectionPool implements ConnectionPool {
    private final Map<String, Connection> pool = new ConcurrentHashMap<>();

    private String getConnectionKey(String remoteIp, int remotePort) {
        return remoteIp + ":" + remotePort;
    }

    @Override
    public void put(Connection connection) {
        pool.put(getConnectionKey(connection.getRemoteIp(), connection.getRemotePort()), connection);
    }

    @Override
    public Connection get(String remoteIp, int remotePort) {
        return pool.get(getConnectionKey(remoteIp, remotePort));
    }

    @Override
    public void remove(String remoteIp, int remotePort) {
        Connection connection = pool.remove(getConnectionKey(remoteIp, remotePort));
        if (connection != null) {
            onClose(connection);
        }
    }

    @Override
    public List<Connection> list() {
        return new ArrayList<>(pool.values());
    }

    @Override
    public int count() {
        return pool.size();
    }

    @Override
    public void shutdown() throws Exception {
        for (Connection connection : pool.values()) {
            connection.close();
            onClose(connection);
        }
    }

    private void onClose(Connection connection) {
        List<ServerConnectionListener> listeners = ServerConnectionListenerProvider.getInstance().list();
        if (listeners != null && listeners.size() > 0) {
            listeners.stream().forEach(listener -> listener.onClose(connection));
        }
    }

}
